package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

// 创建亲友圈统计数据
func NewClubStat(club map[string]interface{}, tableName string, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessLog)
	values, sql := InsertSql(tableName, club)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//更新亲友圈成员数(主要是为了防止成员数不正确)
func UpdateClubCardTable(member, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	sql := fmt.Sprintf("UPDATE %v SET member = %v WHERE id = %v",
		TableClub, member, id)
	result, err := o.Raw(sql).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

// 更新亲友圈
func UpdateClub(club map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChess)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TableClub, club, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

// 改变亲友圈创建人
func ChangeClubHost(clubId, newHost int64) error {
	o := NewDBOrm(DBChess)
	o.Begin()
	defer o.Rollback()
	var hostId int64
	sql := fmt.Sprintf(`SELECT host_id FROM %v WHERE id = %v`, TableClub, clubId)
	err := o.Raw(sql).QueryRow(&hostId)
	if err != nil {
		o.Rollback()
		return err
	}
	sql = fmt.Sprintf(`UPDATE %v SET host_id = %v WHERE id = %v`, TableClub, newHost, clubId)
	_, err = o.Raw(sql).Exec()
	if err != nil {
		o.Rollback()
		return err
	}
	sql = fmt.Sprintf(`UPDATE %v SET role = %v WHERE uid = %v and cid = %v`, TableClubMember, ClubRoleOwner, newHost, clubId)
	_, err = o.Raw(sql).Exec()
	if err != nil {
		o.Rollback()
		return err
	}
	sql = fmt.Sprintf(`UPDATE %v SET role = %v WHERE uid = %v and cid = %v`, TableClubMember, ClubRoleNormal, hostId, clubId)
	_, err = o.Raw(sql).Exec()
	if err != nil {
		o.Rollback()
		return err
	}
	Key := fmt.Sprintf("%v%v", KeyClub, clubId)
	Redis.HSet(Key, "host", newHost)
	o.Commit()
	return nil
}

func ClubById(id int64, multiOrm ...orm.Ormer) (orm.Params, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = ?
		LIMIT 1
		`, TableClub)
	o := NewOrm(multiOrm, DBChess)
	var club []orm.Params
	_, err := o.Raw(sql, id).Values(&club)
	if CheckNoExist(err) {
		return nil, nil
	}
	if len(club) == 1 {
		return club[0], err
	}
	return nil, err
}
func ListClubFloor(p ListParams, clubId, isDelete int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(`club_id = %v `, clubId)
	if isDelete != -1 {
		where = fmt.Sprintf(" club_id = %v AND is_delete = %v ", clubId, isDelete)
	}
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		LIMIT ?,?
		`, TableClubFloor, where)
	o := NewOrm(multiOrm, DBChess)
	var club []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&club)
	if CheckNoExist(err) {
		return club, 0, nil
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v  WHERE %v`, TableClubFloor, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return club, 0, err
	}
	return club, count, nil
}

//列出所有亲友圈
func ListClub(p ListParams, clubId, hostId, status, password int64,
	userName, clubName string, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := "1=1"
	if clubId != 0 {
		where = fmt.Sprintf("c.id = %v", clubId)
	}
	if hostId != 0 {
		where = where + fmt.Sprintf(" AND c.host_id = %v", hostId)
	}
	if status != 0 {
		where = where + fmt.Sprintf(" AND c.status = %v", status)
	}
	if password != 0 {
		where = where + fmt.Sprintf(" AND c.password = %v", password)
	}
	if userName != "" {
		where = where + fmt.Sprintf(" AND u.nickname LIKE '%v'", "%"+userName+"%")
	}
	if clubName != "" {
		where = where + fmt.Sprintf(" AND c.name LIKE '%v'", "%"+clubName+"%")
	}

	sql := fmt.Sprintf(`
		SELECT
			c.*,u.nickname AS host_name
		FROM
			%v AS c
		LEFT JOIN
			%v AS u
		ON c.host_id = u.uid
		WHERE
			%v
		ORDER BY
			c.create_time DESC
		LIMIT ?,?
		`, TableClub, TableClientUser, where)
	o := NewOrm(multiOrm, DBChess)
	var club []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&club)
	if CheckError(err) {
		return club, 0, err
	}
	//此时此刻正在组局的数量,0未结束1正常结束2过期结束3投票解散
	sqlClubTable := fmt.Sprintf(`
			SELECT
				COUNT(1)
			FROM
				%v
			WHERE
				clubid = ? AND isclose = 0
	`, TableRoom)
	var realTimeTable int64 //实时组局正在开打的桌子数
	for _, v := range club {
		o.Raw(sqlClubTable, v["id"]).QueryRow(&realTimeTable)
		v["real_time_table"] = realTimeTable
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v AS c WHERE %v`, TableClub, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return club, 0, err
	}
	return club, count, nil
}

func ListClubMember(p ListParams, clubId, status int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(`cid = %v `, clubId)
	if status != 0 {
		where = fmt.Sprintf(" cid = %v AND status = %v ", clubId, status)
	}
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		LIMIT ?,?
		`, TableClubMember, where)
	o := NewOrm(multiOrm, DBChess)
	var club []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&club)
	if CheckNoExist(err) {
		return club, 0, nil
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v  WHERE %v`, TableClubMember, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return club, 0, err
	}
	return club, count, nil
}
